package com.yango.teach.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yango.teach.client.VodClient;
import com.yango.teach.entity.Video;
import com.yango.teach.mapper.VideoMapper;
import com.yango.teach.service.VideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author LiDingYin
 * @since 2021-07-24
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {

    @Autowired
    private VodClient vodClient;

    //根据id查询该章节下是否有小节，如果有，提示不能删除
    @Override
    public boolean getCountByChapterId(String id) {
        //条件构造器
        QueryWrapper<Video> wrapper = new QueryWrapper<>();
        //根据章节id查询
        wrapper.eq("chapter_id", id);
        //查询满足条件的条数
        Integer count = baseMapper.selectCount(wrapper);
        //返回
        return count > 0 && count != null;
    }

    //根据id删除课时
    @Override
    public boolean removeVideoById(String id) {
        //删除课时视频资源
        //查询云端视频id
        Video video = baseMapper.selectById(id);
        //获取视频id
        String videoSourceId = video.getVideoSourceId();
        if (!StringUtils.isEmpty(videoSourceId)) {//视频id不为空
            //微服务调用方法删除视频
            vodClient.removeVideo(videoSourceId);
        }
        //删除课时信息
        return this.removeById(id);
    }

    //根据课程id删除课时
    @Override
    public boolean removeVideoByCourseId(String courseId) {
        //删除阿里云视频
        //查询课程所有课时
        QueryWrapper<Video> queryWrapper = new QueryWrapper<>();//条件构造器
        queryWrapper.eq("course_id", courseId);//根据课程id查询
        queryWrapper.select("video_source_id");//查询视频id列
        List<Video> videoList = baseMapper.selectList(queryWrapper);//调用方法查询
        //list集合，用于装载视频id
        List<String> videoSourceIds = new ArrayList<>();
        //遍历所有课时，得到视频id
        for (Video video : videoList) {
            //获取视频id
            if (!StringUtils.isEmpty(video.getVideoSourceId())) {
                String videoSourceId = video.getVideoSourceId();
                videoSourceIds.add(videoSourceId);
            }
        }
        if (videoSourceIds.size() > 0) {
            //调用vod服务删除云端视频资源
            vodClient.removeVideoByIds(videoSourceIds);
        }
        //删除课时信息
        //条件构造器
        QueryWrapper<Video> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        //调用方法删除
        Integer count = baseMapper.delete(wrapper);
        return count != null && count > 0;
    }
}
